using System;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

using Ultimate.DAL.CollectionClasses;
using Ultimate.DAL;
using Ultimate.DAL.HelperClasses;
using Ultimate.DAL.EntityClasses;
using Ultimate.DAL.FactoryClasses;
using SD.LLBLGen.Pro.ORMSupportClasses;

using CommunityServer;
using CommunityServer.Components;

namespace Ultimate.League.Controls
{
	/// <summary>
	///		Allows a user to join a league.
	///		If no leagueID is suppled in the query string then the user must first choose a league.
	///		They have 3 options
	///			1. Join as an individual in which case they are added to the "Individuals Team" for the league.
	///			2. Create a team in which case the team is created and they are made the captain of the team.
	///			3. Join an existing team.
	/// </summary>
	public class JoinLeague : System.Web.UI.UserControl
	{
		protected System.Web.UI.WebControls.DataGrid dgLeagues;
		protected System.Web.UI.WebControls.Panel ChooseLeague;
		protected System.Web.UI.WebControls.Panel JoinLeaguePanel;
		protected System.Web.UI.WebControls.Literal Info;
		
		protected System.Web.UI.HtmlControls.HtmlInputRadioButton NewTeam;
		protected System.Web.UI.WebControls.Literal ErrorMessage;
		protected System.Web.UI.WebControls.Button Button1;
		protected System.Web.UI.WebControls.DropDownList TeamName;
		protected System.Web.UI.WebControls.TextBox NewTeamName;
		protected System.Web.UI.HtmlControls.HtmlInputRadioButton Individual;
		protected System.Web.UI.WebControls.Literal LeagueName;
		protected System.Web.UI.WebControls.TextBox FriendsList;
		protected System.Web.UI.HtmlControls.HtmlInputRadioButton Team;
        protected System.Web.UI.WebControls.Panel updateProfileMessage;


		public int LeagueID
		{
			get
			{
				return Convert.ToInt32(ViewState["LeagueID"]);
			}
			set
			{
				ViewState["LeagueID"] = value;
			}
		}
		/// <summary>
		/// On page load the leagueID is determined and BindData is called.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void Page_Load(object sender, System.EventArgs e)
		{
            if (!Player.IsUpdated)
            {
                ChooseLeague.Visible = false;
                JoinLeaguePanel.Visible = false;
                updateProfileMessage.Visible = true;
            }
            else
            {
                ChooseLeague.Visible = true;
                JoinLeaguePanel.Visible = true;
                updateProfileMessage.Visible = false;

                if (!this.IsPostBack)
                {
                    LeagueID = -1;
                    if (Request.QueryString["LeagueID"] != null)
                    {
                        this.LeagueID = Convert.ToInt32(Request.QueryString["LeagueID"]);
                    }

                    BindData();
                }
            }

		}

		/// <summary>
		/// If the leagueID is -1 then a listing of the available leagues is displayed
		/// Otherwise we check to see if the user is already in the league, if they are then a message is displayed to that affect
		/// If they don't already belong to the league then we populate the availble teams list
		/// </summary>
		private void BindData()
		{
			if (LeagueID == -1)
			{
				
				ChooseLeague.Visible=true;
				JoinLeaguePanel.Visible=false;
				LeagueCollection lc = new LeagueCollection();
				PredicateExpression filter = new PredicateExpression();
                filter.Add(PredicateFactory.CompareValue(LeagueFieldIndex.RegistrationOpen, ComparisonOperator.Equal, true));
                filter.AddWithAnd(PredicateFactory.CompareValue(LeagueFieldIndex.Active, ComparisonOperator.Equal, true));


                lc.GetMulti(filter);
				dgLeagues.DataSource=lc.Items;
				dgLeagues.DataBind();
			}
			else
			{
				JoinLeaguePanel.Visible=true;
				ChooseLeague.Visible=false;

                System.Web.Security.MembershipUser mu = System.Web.Security.Membership.GetUser();
                Guid userID = (Guid)mu.ProviderUserKey;

				LeagueCollection lc = new LeagueCollection();
				PredicateExpression A = new PredicateExpression();
				A.Add(PredicateFactory.CompareValue(LeagueFieldIndex.LeagueID  , ComparisonOperator.Equal, LeagueID));
				A.AddWithAnd(PredicateFactory.CompareValue(PlayerFieldIndex.UserID  , ComparisonOperator.Equal, userID));
				IRelationCollection relations = new RelationCollection();
				relations.Add(LeagueEntity.Relations.TeamEntityUsingLeagueID);
				relations.Add(TeamEntity.Relations.TeamPlayerEntityUsingTeamID);
                relations.Add(TeamPlayerEntity.Relations.PlayerEntityUsingUserID);
				if (lc.GetDbCount(A,relations)> 0)
				{
					//Already in this league.
					JoinLeaguePanel.Visible=false;
					ChooseLeague.Visible=false;
					ErrorMessage.Text="You already belong to this league.";
				}

												
				LeagueEntity le = new LeagueEntity(this.LeagueID);


				LeagueName.Text = "Join "+le.Name;
				Info.Text = le.Info;
				
				TeamCollection tc = new TeamCollection();
				PredicateExpression B = new PredicateExpression();
				B.Add(PredicateFactory.CompareValue(TeamFieldIndex.LeagueID , ComparisonOperator.Equal, this.LeagueID));
				B.AddWithAnd(PredicateFactory.CompareValue(TeamFieldIndex.TeamName  , ComparisonOperator.NotEqual, "Individuals"));
				tc.GetMulti(B);
				TeamName.DataSource=tc.Items;
				TeamName.DataTextField="TeamName";
				TeamName.DataValueField="TeamID";
				TeamName.DataBind();
				
			}
		}

		/// <summary>
		/// Makes the user a member of the league and a team depending on their choices.
		/// </summary>
		/// <param name="o"></param>
		/// <param name="e"></param>
		protected void Join(System.Object o, System.EventArgs e)
		{
			TeamPlayerEntity tpe = new TeamPlayerEntity();
			if (Individual.Checked==true)
			{
				TeamCollection tc = new TeamCollection();
				PredicateExpression A = new PredicateExpression();
				A.Add(PredicateFactory.CompareValue(TeamFieldIndex.LeagueID , ComparisonOperator.Equal, this.LeagueID));
				A.AddWithAnd(PredicateFactory.CompareValue(TeamFieldIndex.TeamName  , ComparisonOperator.Equal, "Individuals"));
				tc.GetMulti(A);
				if (tc.Count >0)
				{
					tpe.TeamID= tc[0].TeamID;
					tpe.RoleID= (int)Ultimate.Roles.Individual;
					tpe.FriendsList=FriendsList.Text;
                    ErrorMessage.Text = "You have been registered in <a href=\"" + this.ResolveUrl("~/RegistrationSystem/league/editleague.aspx?leagueID=" + tpe.Team.LeagueID.ToString()) + "\">" + tpe.Team.League.Name + "</a> as an individual";
				}
				else
				{
					ErrorMessage.Text="This league is not accepting individual registration.";
					return;
				}			
			}
			else if (Team.Checked==true)
			{
				tpe.TeamID = Convert.ToInt32(TeamName.SelectedValue);
                tpe.RoleID = (int)Ultimate.Roles.Player;
                ErrorMessage.Text = "You have been registered in <a href=\"" + this.ResolveUrl("~/RegistrationSystem/league/editleague.aspx?leagueID=" + tpe.Team.LeagueID.ToString()) + "\">" + tpe.Team.League.Name + "</a> on team <a href=\"" + this.ResolveUrl("~/RegistrationSystem/team/editteam.aspx?teamID=" + tpe.TeamID.ToString()) + "\">" + tpe.Team.TeamName + "</a>.";
			}
			else
			{
				TeamEntity te = new TeamEntity();
				te.LeagueID=this.LeagueID;
				te.TeamName=NewTeamName.Text;
				te.Save();

				tpe.TeamID=te.TeamID;
                tpe.RoleID = (int)Ultimate.Roles.Captain;
				ErrorMessage.Text="You have been registered in <a href=\""+this.ResolveUrl("~/RegistrationSystem/league/editleague.aspx?leagueID="+tpe.Team.LeagueID.ToString())+"\">"+tpe.Team.League.Name+"</a> and you are the captain of <a href=\""+this.ResolveUrl("~/RegistrationSystem/team/editteam.aspx?teamID="+tpe.TeamID.ToString())+"\">"+tpe.Team.TeamName+"</a>.";
			}
			tpe.UserID=Player.UserID;
            tpe.WaiverSigned = true;
			tpe.Save();

			JoinLeaguePanel.Visible=false;
			
			
		}

        /// <summary>
        /// A league link button was clicked display teh details for that league.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnLeague_Command(object sender, CommandEventArgs e)
        {
            int id;
            if (!int.TryParse(e.CommandArgument.ToString(), out id))
            {
                id = -1;
            }

            LeagueID = id;
            BindData();
        }

        /// <summary>
        /// Resets the control back to it's original state.
        /// </summary>
        public void Reset()
        {
            if (!Player.IsUpdated)
            {
                ChooseLeague.Visible = false;
                JoinLeaguePanel.Visible = false;
                updateProfileMessage.Visible = true;
            }
            else
            {
                ChooseLeague.Visible = true;
                JoinLeaguePanel.Visible = true;
                updateProfileMessage.Visible = false;
             
                LeagueID = -1;
                BindData();
            }
        }

        private PlayerEntity _pe;
        private PlayerEntity Player
        {
            get
            {
                if (_pe == null)
                {
                    _pe = new PlayerEntity();
                    System.Web.Security.MembershipUser mu = System.Web.Security.Membership.GetUser();
                    _pe.FetchUsingUCUserID((Guid)mu.ProviderUserKey);
                }

                return _pe;
            }
        }

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		///		Required method for Designer support - do not modify
		///		the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.Load += new System.EventHandler(this.Page_Load);

		}
		#endregion
	}
}
